package huizhi.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * TODO
 *
 * @author YuXD
 * @since 2023/12/25
 */
public class SocketServer3 {

    public static void main(String[] args) throws IOException {
        System.out.println("我是SocketServer");
        // 启动服务端，监听8888端口
        ServerSocket server = new ServerSocket(8888);
        // 服务端待命，等待客户端连接。在套接字连接之前，都处于阻塞状态
        Socket accept = server.accept();

        // 获取客户端输入字节流
        InputStream inputStream = accept.getInputStream();
        // buffer
        byte[] buf = new byte[1024];
        // 读取到buf中的字节数
        int readLength;
        while (-1 != (readLength = inputStream.read(buf))) {
            System.out.println(new String(buf, 0, readLength));
        }

        // 从套接字获取字节输出流
        OutputStream outputStream = accept.getOutputStream();
        outputStream.write("hello, client！".getBytes(Charset.defaultCharset()));

        inputStream.close();
        accept.close();
        server.close();
    }

}
